<template>
    <div class="media-manager">
        <!-- 顶部操作栏 -->
        <div class="toolbar">
            <el-upload action="/api/upload" :show-file-list="false" :on-success="handleUploadSuccess"
                :before-upload="beforeUpload" multiple>
                <el-button type="primary" plain>
                    <el-icon>
                        <Upload />
                    </el-icon>
                    上传
                </el-button>
            </el-upload>

            <el-dropdown @command="handleBatchCommand">
                <el-button plain>
                    批量操作<el-icon>
                        <ArrowDown />
                    </el-icon>
                </el-button>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="rename">批量重命名</el-dropdown-item>
                        <el-dropdown-item command="download">批量下载</el-dropdown-item>
                        <el-dropdown-item command="delete" divided>批量删除</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>

            <el-button plain @click="refreshList">
                <el-icon>
                    <Refresh />
                </el-icon>
                刷新
            </el-button>

            <el-input v-model="searchQuery" placeholder="搜索文件名称" clearable class="search-input" @clear="handleSearchClear"
                @keyup.enter="handleSearch">
                <template #prefix>
                    <el-icon>
                        <Search />
                    </el-icon>
                </template>
            </el-input>
        </div>

        <!-- 批量操作栏 -->
        <div v-if="selectedItems.length > 0" class="batch-actions">
            <span class="selected-count">已选 {{ selectedItems.length }} 项</span>
            <el-button size="small" @click="handleBatchDownload">
                <el-icon>
                    <Download />
                </el-icon>
                批量下载
            </el-button>
            <el-button size="small" type="danger" plain @click="handleBatchDelete">
                <el-icon>
                    <Delete />
                </el-icon>
                批量删除
            </el-button>
        </div>

        <!-- 媒体列表 -->
        <el-table :data="filteredMediaList" style="width: 100%" @selection-change="handleSelectionChange"
            v-loading="loading" :header-cell-style="{ background: '#f5f7fa' }">
            <el-table-column type="selection" width="55" />

            <el-table-column label="缩略图" width="120">
                <template #default="{ row }">
                    <div class="thumbnail" @click="handlePreview(row)">
                        <img v-if="row.type === 'image'" :src="row.thumbnail || row.url" class="thumbnail-image" />
                        <div v-else class="video-thumbnail">
                            <el-icon size="40">
                                <VideoPlay />
                            </el-icon>
                        </div>
                        <div class="file-type-tag">
                            <el-tag size="small" :type="row.type === 'image' ? 'success' : 'warning'">
                                {{ row.type === 'image' ? '图片' : '视频' }}
                            </el-tag>
                        </div>
                    </div>
                </template>
            </el-table-column>

            <el-table-column prop="name" label="文件名称">
                <template #default="{ row }">
                    <div v-if="row.editing" class="editing-name">
                        <el-input v-model="row.newName" size="small" @keyup.enter="confirmRename(row)"
                            @blur="confirmRename(row)" autofocus />
                    </div>
                    <div v-else class="file-name" @dblclick="startEditing(row)">
                        {{ row.name }}
                    </div>
                </template>
            </el-table-column>

            <el-table-column prop="size" label="大小" width="120">
                <template #default="{ row }">
                    {{ formatFileSize(row.size) }}
                </template>
            </el-table-column>

            <el-table-column prop="uploadTime" label="上传时间" width="180" sortable>
                <template #default="{ row }">
                    {{ formatDateTime(row.uploadTime) }}
                </template>
            </el-table-column>

            <el-table-column label="操作" width="150">
                <template #default="{ row }">
                    <el-button v-if="row.type === 'video'" link type="primary" size="small" @click="playVideo(row)">
                        播放
                    </el-button>

                    <el-dropdown trigger="click">
                        <el-button link type="primary" size="small">
                            更多<el-icon>
                                <ArrowDown />
                            </el-icon>
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item @click="startEditing(row)">重命名</el-dropdown-item>
                                <el-dropdown-item @click="handleDownload(row)">下载</el-dropdown-item>
                                <el-dropdown-item @click="handleDelete(row)" divided>删除</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="totalItems"
                :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 预览对话框 -->
        <el-dialog v-model="previewVisible" title="图片预览" width="70%">
            <img :src="previewImageUrl" style="max-width: 100%;" />
        </el-dialog>

        <!-- 视频播放对话框 -->
        <el-dialog v-model="videoVisible" title="视频播放" width="70%">
            <video controls autoplay style="width: 100%;">
                <source :src="currentVideoUrl" type="video/mp4">
                您的浏览器不支持视频播放
            </video>
        </el-dialog>

        <!-- 批量重命名对话框 -->
        <el-dialog v-model="batchRenameVisible" title="批量重命名" width="400px">
            <el-form label-width="80px">
                <el-form-item label="命名规则">
                    <el-input v-model="batchRenamePattern" placeholder="例如: 图片{num}" />
                </el-form-item>
                <el-form-item label="起始序号">
                    <el-input-number v-model="batchRenameStart" :min="1" />
                </el-form-item>
                <el-form-item label="预览">
                    <div class="rename-preview">
                        <p v-for="(item, index) in renamePreview" :key="index">
                            {{ item.oldName }} → {{ item.newName }}
                        </p>
                    </div>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="batchRenameVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmBatchRename">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>
  
<script setup>
import { ref, computed, watch } from 'vue'
import {
    Upload, ArrowDown, Refresh, Search,
    VideoPlay, Download, Delete
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 模拟数据
const mockData = [
    {
        id: 1,
        name: '假期.jpg',
        url: 'https://example.com/images/holiday.jpg',
        thumbnail: 'https://example.com/thumbs/holiday.jpg',
        type: 'image',
        size: 2456789,
        uploadTime: '2023-05-12T10:25:36'
    },
    {
        id: 2,
        name: '会议记录.mp4',
        url: 'https://example.com/videos/meeting.mp4',
        thumbnail: 'https://example.com/thumbs/meeting.jpg',
        type: 'video',
        size: 12567890,
        uploadTime: '2023-05-11T15:42:09'
    },
    {
        id: 3,
        name: '截图.png',
        url: 'https://example.com/images/screenshot.png',
        thumbnail: 'https://example.com/thumbs/screenshot.png',
        type: 'image',
        size: 1567890,
        uploadTime: '2023-05-10T09:12:45'
    }
]

// 响应式数据
const mediaList = ref([])
const loading = ref(false)
const selectedItems = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(0)
const previewVisible = ref(false)
const previewImageUrl = ref('')
const videoVisible = ref(false)
const currentVideoUrl = ref('')
const batchRenameVisible = ref(false)
const batchRenamePattern = ref('图片{num}')
const batchRenameStart = ref(1)
const renamePreview = ref([])

// 计算属性
const filteredMediaList = computed(() => {
    let result = mediaList.value

    if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(item => item.name.toLowerCase().includes(query))
    }

    totalItems.value = result.length
    return result.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value)
})

// 监听批量重命名模式变化
watch([batchRenamePattern, batchRenameStart], () => {
    updateRenamePreview()
})

// 方法
const fetchMediaList = async () => {
    loading.value = true
    try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 500))
        mediaList.value = mockData.map(item => ({
            ...item,
            editing: false,
            newName: item.name
        }))
        totalItems.value = mediaList.value.length
    } catch (error) {
        ElMessage.error('获取媒体列表失败')
    } finally {
        loading.value = false
    }
}

const refreshList = () => {
    currentPage.value = 1
    fetchMediaList()
}

const handleUploadSuccess = (response, file) => {
    const newItem = {
        id: Date.now(),
        name: file.name,
        url: URL.createObjectURL(file.raw),
        thumbnail: file.type.startsWith('image/') ? URL.createObjectURL(file.raw) : '',
        type: file.type.startsWith('image/') ? 'image' : 'video',
        size: file.size,
        uploadTime: new Date().toISOString(),
        editing: false,
        newName: file.name
    }

    mediaList.value.unshift(newItem)
    ElMessage.success(`${file.name} 上传成功`)
}

const beforeUpload = (file) => {
    const isMedia = file.type.startsWith('image/') || file.type.startsWith('video/')
    const isLt50M = file.size / 1024 / 1024 < 50

    if (!isMedia) {
        ElMessage.error('只能上传图片或视频文件!')
        return false
    }
    if (!isLt50M) {
        ElMessage.error('文件大小不能超过50MB!')
        return false
    }

    return true
}

const handleSelectionChange = (selection) => {
    selectedItems.value = selection
}

const handlePreview = (item) => {
    if (item.type === 'image') {
        previewImageUrl.value = item.url
        previewVisible.value = true
    } else {
        playVideo(item)
    }
}

const playVideo = (item) => {
    if (item.type === 'video') {
        currentVideoUrl.value = item.url
        videoVisible.value = true
    }
}

const startEditing = (item) => {
    mediaList.value.forEach(i => i.editing = false)
    item.editing = true
    item.newName = item.name
}

const confirmRename = async (item) => {
    if (!item.newName || item.newName === item.name) {
        item.editing = false
        return
    }

    try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 300))
        item.name = item.newName
        item.editing = false
        ElMessage.success('重命名成功')
    } catch (error) {
        ElMessage.error('重命名失败')
    }
}

const handleDelete = async (item) => {
    try {
        await ElMessageBox.confirm(`确定删除 "${item.name}" 吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 300))
        mediaList.value = mediaList.value.filter(i => i.id !== item.id)
        selectedItems.value = selectedItems.value.filter(i => i.id !== item.id)
        ElMessage.success('删除成功')
    } catch {
        // 用户取消
    }
}

const handleBatchCommand = (command) => {
    if (selectedItems.value.length === 0) {
        ElMessage.warning('请先选择文件')
        return
    }

    switch (command) {
        case 'rename':
            batchRenamePattern.value = '图片{num}'
            batchRenameStart.value = 1
            batchRenameVisible.value = true
            break
        case 'download':
            handleBatchDownload()
            break
        case 'delete':
            handleBatchDelete()
            break
    }
}

const handleBatchDownload = () => {
    ElMessage.success(`开始批量下载 ${selectedItems.value.length} 个文件`)
    // 实际实现中这里应该调用下载API
}

const handleBatchDelete = async () => {
    try {
        await ElMessageBox.confirm(`确定删除选中的 ${selectedItems.value.length} 个文件吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 300))
        const selectedIds = selectedItems.value.map(item => item.id)
        mediaList.value = mediaList.value.filter(i => !selectedIds.includes(i.id))
        selectedItems.value = []
        ElMessage.success('批量删除成功')
    } catch {
        // 用户取消
    }
}

const updateRenamePreview = () => {
    renamePreview.value = selectedItems.value.slice(0, 3).map((item, index) => {
        const extension = item.name.split('.').pop()
        let newName = batchRenamePattern.value
            .replace('{num}', batchRenameStart.value + index)
            .replace('{name}', item.name.replace(/\.[^/.]+$/, ''))
        newName = newName + '.' + extension
        return { oldName: item.name, newName }
    })
}

const confirmBatchRename = async () => {
    try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 500))

        selectedItems.value.forEach((item, index) => {
            const extension = item.name.split('.').pop()
            item.newName = batchRenamePattern.value
                .replace('{num}', batchRenameStart.value + index)
                .replace('{name}', item.name.replace(/\.[^/.]+$/, ''))
            item.newName = item.newName + '.' + extension
            item.name = item.newName
        })

        batchRenameVisible.value = false
        ElMessage.success('批量重命名成功')
    } catch (error) {
        ElMessage.error('批量重命名失败')
    }
}

const handleDownload = (item) => {
    ElMessage.success(`开始下载 ${item.name}`)
    // 实际实现中这里应该调用下载API
}

const handleSearch = () => {
    currentPage.value = 1
}

const handleSearchClear = () => {
    searchQuery.value = ''
    currentPage.value = 1
}

const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
}

const handleCurrentChange = (val) => {
    currentPage.value = val
}

const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatDateTime = (dateTime) => {
    const date = new Date(dateTime)
    return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
}

// 初始化
fetchMediaList()
</script>
  
<style scoped>
.media-manager {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.toolbar {
    display: flex;
    gap: 10px;
    margin-bottom: 15px;
    flex-wrap: wrap;
}

.search-input {
    width: 250px;
    margin-left: auto;
}

.batch-actions {
    padding: 8px 12px;
    background-color: #f5f7fa;
    border-radius: 4px;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 15px;
}

.selected-count {
    font-size: 14px;
    color: #606266;
}

.thumbnail {
    position: relative;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    background-color: #f8f8f8;
    border-radius: 4px;
    overflow: hidden;
}

.thumbnail-image {
    max-height: 100%;
    max-width: 100%;
    object-fit: contain;
}

.video-thumbnail {
    color: var(--el-color-primary);
}

.file-type-tag {
    position: absolute;
    bottom: 4px;
    right: 4px;
}

.file-name {
    cursor: text;
    padding: 5px 0;
}

.editing-name {
    margin: -5px 0;
}

.rename-preview {
    max-height: 120px;
    overflow-y: auto;
    border: 1px solid #ebeef5;
    padding: 8px;
    border-radius: 4px;
    font-size: 13px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>